/*
 * @Author: fuhongliang-TSJ hongliang.fu@4d-bios.com
 * @Date: 2025-09-22 16:30:35
 * @LastEditTime: 2025-09-23 15:00:33
 * @LastEditors: fuhongliang-TSJ hongliang.fu@4d-bios.com
 * @Description: 
 * @FilePath: \lc_-esp32_-s3\main\blufi\blufi_key.c
 * 立创实战派ESP32-S3开发板
 * Copyright (c) 2025 by 4D Bios, All Rights Reserved. 
 */

#include "iot_button.h"
#include "button_gpio.h"
#include "driver/gpio.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "blufi.h"
#include "esp_log.h"

#define BOOT_BUTTON_NUM         GPIO_NUM_0
#define BUTTON_ACTIVE_LEVEL     0

static const char *TAG = "blufi_key";

extern EventGroupHandle_t blufi_event_group ; 
extern EventBits_t  blufi_event_bit; 

 /**
 * @description: 长按键注册回调函数
 * @param {void} *arg
 * @param {void} *data
 * @return {*}
 */
static void button_long_press_cb(void *arg, void *data)
{
    iot_button_print_event((button_handle_t)arg);

    //esp_wifi_disconnect();
    //esp_wifi_stop();

    if (blufi_event_bit & BLUFI_NET_CONFIG_BIT_CONFIGING)
    {
        ESP_LOGE(TAG, "--- EXIT Blufi, Return to Normal Work Mode ---");
        
        //BLUFI_NET_CONFIG_BIT_CLOSE 会关闭蓝牙配网功能
        xEventGroupClearBits(blufi_event_group, 0xFFFF);
        xEventGroupSetBits(blufi_event_group, BLUFI_NET_CONFIG_BIT_CLOSE);  
   
        return;
    }

    xEventGroupClearBits(blufi_event_group, 0xFFFF);
    xEventGroupSetBits(blufi_event_group, BLUFI_NET_CONFIG_BIT_STARTUP);

    ESP_LOGE(TAG,"### Blufi Net-Config after 1s ###\n");
    vTaskDelay(pdMS_TO_TICKS(1000));
}

 /**
 * @description: 短按键注册回调函数
 * @param {void} *arg
 * @param {void} *data
 * @return {*}
 */
static void button_single_click_cb(void *arg, void *data)
{
    iot_button_print_event((button_handle_t)arg);
}

/**
 * @description: 按键初始化
 * @param {uint32_t} button_num
 * @return {*}
 */
static void button_init(uint32_t button_num)
{
    button_config_t btn_cfg = {
        .long_press_time = 3000,
        .short_press_time = 0,
    };

    button_gpio_config_t gpio_cfg = {
        .gpio_num = button_num,
        .active_level = BUTTON_ACTIVE_LEVEL,
        .enable_power_save = false,
    };

    button_handle_t btn;
    esp_err_t ret = iot_button_new_gpio_device(&btn_cfg, &gpio_cfg, &btn);
    assert(ret == ESP_OK);

    ret = iot_button_register_cb(btn, BUTTON_LONG_PRESS_START, NULL, button_long_press_cb, NULL);
    ret = iot_button_register_cb(btn, BUTTON_SINGLE_CLICK, NULL, button_single_click_cb, NULL);

    ESP_ERROR_CHECK(ret);
}
/**
 * @description: 按键初始化
 * @return {*}
 */
void blufi_key_init(void)
{
    button_init(BOOT_BUTTON_NUM);
}